package zpx.dao;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import zpx.idao.IUserDao;
import zpx.model.Pager;
import zpx.model.SystemContext;
import zpx.model.User;


@Repository("userDao")
public class UserDao extends HibernateDaoSupport implements IUserDao {
	
	@Resource
	public void setSuperSessionFactory(SessionFactory sessionFactory) {
		this.setSessionFactory(sessionFactory);
	}
	
	@Override
	public void add(User user) {
		this.getHibernateTemplate().save(user);
	}

	@Override
	public void update(User user) {
		this.getHibernateTemplate().update(user);
	}

	@Override
	public void delete(String id) {
		User user = this.load(id);
		this.getHibernateTemplate().delete(user);
	}

	@Override
	public User load(String id) {
		return this.getHibernateTemplate().load(User.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> list() {
		return this.getSessionFactory().getCurrentSession().createQuery("from User").list();
	}
	
	@Override
	public List<User> getUserList(Map<String, String> searchMap){
		Query query = this.getSessionFactory().getCurrentSession().createQuery("from User");
        if (query != null) {
            String startIndex = (String) searchMap.get("startIndex");
            String pageSize = (String) searchMap.get("pageSize");
            if (StringUtils.hasText(startIndex) && StringUtils.hasText(pageSize)) {
                query.setMaxResults(Integer.parseInt(pageSize));
                query.setFirstResult(Integer.parseInt(startIndex));
            }
        }
        List<User> datas = query.list();
        return datas;
	}
	
	@Override
	public int getUserCount(){
		int total = 0;
		Long datacount= (Long) this.getSessionFactory().getCurrentSession()
				.createQuery("select count(*) from User")
				.uniqueResult();
		total=datacount.intValue();
		return total;
	}

	@Override
	public User loadByUsername(String username) {
		return (User)this.getSessionFactory().getCurrentSession().createQuery("from User where username=?")
					.setParameter(0, username).uniqueResult();
	}

}
